//
//  InviteVC.swift
//  kxf
//
//  Created by Mac on 2024/3/9.
//

import Foundation
import UIKit
import Photos
import MCToast

class InviteVC: WHBaseViewVC {
    
    var type = "0"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        sendQrcodeRequest()
    }
    
    lazy var bgImgView : UIImageView = {
        let img = UIImageView()
        img.setImgLocal(imgName: "invite_bg_img")
        img.isUserInteractionEnabled = true
        
        return img
    }()
    lazy var segmentVm : TypeSegmentVM = {
        let vm = TypeSegmentVM.init(frame: CGRect.init(x: kFitWidth(65), y: kFitWidth(45), width: 0, height: 0))
        vm.leftTapBlock = {()in
            self.type = "0"
//            self.shareImgView.setImgLocal(imgName: "invite_merc_img")
            self.sendQrcodeRequest()
        }
        vm.rightTapBlock = {()in
            self.type = "1"
//            self.shareImgView.setImgLocal(imgName: "invite_agent_img")
            self.sendQrcodeRequest()
        }
        return vm
    }()
    lazy var shareImgView : UIImageView = {
        let img = UIImageView()
        img.setImgLocal(imgName: "invite_merc_img")
        img.contentMode = .scaleAspectFit
        img.isUserInteractionEnabled = true
        
        return img
    }()
    lazy var shareQrCodeImgView : UIImageView = {
        let img = UIImageView()
        img.isHidden = true
        img.image = generateQRCode("hfouwwejifwejowiowefiowoenwofnweoinfwo")
        return img
    }()
    lazy var shareLabel : UILabel = {
        let lab = UILabel()
        lab.text = "扫码注册"
        lab.isHidden = true
        lab.textColor = .white
        lab.font = .systemFont(ofSize: 16, weight: .medium)
        
        return lab
    }()
    lazy var saveBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("下载保存", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        btn.setBackgroundImage(UIImage.init(named: "qrcode_btn_bg"), for: .normal)
        btn.backgroundColor = .clear
        btn.titleEdgeInsets = UIEdgeInsets(top: -kFitWidth(5), left: 0, bottom: 0, right: 0)
        
        btn.addTarget(self, action: #selector(saveAction), for: .touchUpInside)
        
        return btn
    }()
    lazy var shareBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("分享转发", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        btn.setBackgroundImage(UIImage.init(named: "qrcode_btn_bg"), for: .normal)
        btn.backgroundColor = .clear
        btn.titleEdgeInsets = UIEdgeInsets(top: -kFitWidth(5), left: 0, bottom: 0, right: 0)
        
        btn.addTarget(self, action: #selector(shareAction), for: .touchUpInside)
        
        return btn
    }()
}

extension InviteVC{
    @objc func shareAction()  {
        let message =  WXMediaMessage()
        
        let imageObject =  WXImageObject()
        let img = shareImgView.mc_makeImage()
        imageObject.imageData = img.pngData()!
        message.mediaObject = imageObject
        let req =  SendMessageToWXReq()
        req.bText = false
        req.message = message
        req.scene = Int32(WXSceneSession.rawValue)
        WXApi.send(req)

    }
}
extension InviteVC{
    func initUI() {
        initNavi(titleStr: "邀请")
        
        view.addSubview(scrollView)
        scrollView.addSubview(bgImgView)
        bgImgView.addSubview(segmentVm)
        
        bgImgView.addSubview(shareImgView)
        shareImgView.addSubview(shareQrCodeImgView)
        shareImgView.addSubview(shareLabel)
        
        scrollView.addSubview(saveBtn)
        scrollView.addSubview(shareBtn)
        
        scrollView.backgroundColor = WHColorWithAlpha(colorStr: "F10E0E", alpha: 0.09)
        scrollView.frame = CGRect.init(x: 0, y: getNavigationBarHeight(), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-getNavigationBarHeight())
        scrollView.contentSize = CGSize.init(width: 0, height: kFitWidth(905)-getNavigationBarHeight())
        
        setConstrait()
    }
    func setConstrait() {
        bgImgView.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.top.equalTo(kFitWidth(22))
            make.width.equalTo(kFitWidth(343))
            make.height.equalTo(kFitWidth(663))
        }
        shareImgView.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.width.equalTo(kFitWidth(268))
            make.height.equalTo(kFitWidth(476))
            make.top.equalTo(kFitWidth(151))
        }
        shareQrCodeImgView.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.top.equalTo(kFitWidth(286))
            make.width.height.equalTo(kFitWidth(134))
        }
        shareLabel.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.top.equalTo(shareQrCodeImgView.snp.bottom).offset(kFitWidth(10))
        }
        saveBtn.snp.makeConstraints { make in
            make.left.equalTo(kFitWidth(35))
            make.top.equalTo(shareImgView.snp.bottom).offset(kFitWidth(66))
            make.width.equalTo(kFitWidth(108))
            make.height.equalTo(kFitWidth(44))
        }
        shareBtn.snp.makeConstraints { make in
            make.left.equalTo(kFitWidth(205))
            make.width.height.equalTo(saveBtn)
            make.centerY.lessThanOrEqualTo(saveBtn)
        }
    }
}

extension InviteVC{
    @objc func saveAction() {
        PHPhotoLibrary.requestAuthorization { (status) in
            DispatchQueue.main.async {
                if status == .restricted || status == .denied{
                    self.presentAlertVc(confirmBtn: "打开", message: "无访问相册权限，是否去打开权限?", title: "提示", cancelBtn: "取消", handler: { (actions) in
                        self.openUrl(urlString: UIApplication.openSettingsURLString)
                    }, viewController: self)
                }else{
                    MCToast.mc_loading(text: "保存中", autoClearTime: 30)
                    let image = self.shareImgView.mc_makeImage()
                    UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
                }
            }
        }
    }
    @objc private func saveImage(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject){
        MCToast.mc_remove()
        if error != nil{
            self.presentAlertVcNoAction(title: "保存失败", viewController: self)
        }else{
            MCToast.mc_text("已保存到相册！")
        }
    }
}

extension InviteVC{
    func sendQrcodeRequest() {
        MCToast.mc_loading()
        
        let param = ["type":"\(type)"]
        
        WHNetworkUtil.shareManager().POST(urlString: URL_get_invite_qrcode, parameters: param as? [String : AnyObject],isNeedToast: true,vc:self) { responseObject in
            DLLog(message: "\(responseObject)")
            self.shareImgView.setImgUrl(urlString: "\(responseObject["data"]as? String ?? "")")
        }
    }
}
